
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getRoleApi, getUserInfoApi } from "@/api/auth";
import { getCompanyListApi } from '@/api/company';
import { useCompanyStore } from './company';
export const useUserStore = defineStore('user', () => {
    // 用户信息
    let userinfo = ref(null);
    let role = ref(null);
    // 默认权限
    let userPermissions = ref(0);
    let userCompany = ref(null);
    let companyStore = useCompanyStore();
    //是否绑定微信
    let wechat_bind = ref(false)

    function setWechatBind(bind) {
        wechat_bind.value = bind
    }
    // 设置用户信息并根据用户信息设置权限
    const setUserInfo = async (data) => {
        userinfo.value = data;
        if (data.permission) {
            userPermissions.value = data.permission;
        }
        if (data.company_id) {
            let res = await getCompanyListApi({ id: data.company_id })
            if (res.code === 200) {
                userCompany.value = res.data.companies[0];
                companyStore.setCurrentCompany(userCompany.value);
            } else {
                throw new Error(res.message);
            }
        }
    };

    // 获取用户信息
    async function getUserInfo() {
        let res = await getUserInfoApi();
        let roleRes = await getRoleApi({
            username: res.results[0].username
        })
        if (roleRes.code === 200) {
            role.value = roleRes.data[0]
        }
        if (res.code === 200) {
            await setUserInfo(res.results[0]);
        } else {
            console.error('获取用户信息失败', res);
        }
        return res.results[0];
    }

    return {
        userinfo,
        role,
        userCompany,
        userPermissions,
        wechat_bind,
        setWechatBind,
        setUserInfo,
        getUserInfo,
    };
}, {
    persist: true, // 数据持久化
});
